﻿using System;

namespace OS.Common.Extention
{
    /// <summary>
    /// 时间秒数转换扩展类
    /// </summary>
    public static class DateTimeExtention
    {
        private static readonly long StartTicks = new DateTime(1970, 1, 1).Ticks;

        /// <summary>
        /// 获取距离 1970-01-01（格林威治时间）的秒数
        /// </summary>
        /// <param name="localTime">本地时间</param>
        /// <returns></returns>
        public static long ToUtcSeconds(this DateTime localTime)
        {
            return (localTime.ToUniversalTime().Ticks - StartTicks) / 10000000;
        }

        /// <summary>
        /// 距离 1970-01-01（格林威治时间）的秒数转换为当前时间
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns></returns>
        public static DateTime FromUtcSeconds(this long seconds)
        {
            return DateTimeOffset.FromUnixTimeSeconds(seconds).LocalDateTime;
        }

        /// <summary>
        /// 获取距离 1970-01-01（格林威治时间）的秒数
        /// </summary>
        /// <param name="localTime">本地时间</param>
        /// <returns></returns>
        public static long ToUtcMilliSeconds(this DateTime localTime)
        {
            return (localTime.ToUniversalTime().Ticks - StartTicks) / 10000;
        }

        /// <summary>
        /// 距离 1970-01-01（格林威治时间）的秒数转换为当前时间
        /// </summary>
        /// <param name="milliSeconds">毫秒数</param>
        /// <returns></returns>
        public static DateTime FromUtcMilliSeconds(this long milliSeconds)
        {
            return DateTimeOffset.FromUnixTimeMilliseconds(milliSeconds).LocalDateTime;
        }

        /// <summary>
        /// 获取距离 1970-01-01（本地/北京时间）的秒数
        /// </summary>
        /// <param name="localTime">本地时间</param>
        /// <returns></returns>
        public static long ToLocalSeconds(this DateTime localTime)
        {
            return (localTime.Ticks - StartTicks) / 10000000;
        }

        /// <summary>
        /// 距离 1970-01-01（本地/北京时间）的秒数转换为当前时间
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns></returns>
        public static DateTime FromLocalSeconds(this long seconds)
        {
            return new DateTime(1970, 1, 1).AddSeconds(seconds);
        }
    }
}